package activator;

import library.service.Book;
import library.service.LibraryService;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;

public class Activator implements BundleActivator {

	private static final String BOOK_NAME_OLD = "Cooking";
	private static final String BOOK_NAME_NEW = "OSGi";
	ServiceReference libServiceRef;
	LibraryService libService;

	public void start(BundleContext context) throws Exception {
		libServiceRef = context.getServiceReference(LibraryService.class
				.getName());

		if (libServiceRef != null) {
			System.out.println("CONSUMER-1: getService() method called.");
			libService = (LibraryService) context.getService(libServiceRef);

			if (libService != null) {
				Book foundBook = libService.findBookByName(BOOK_NAME_OLD);
				if (foundBook != null) {
					System.out.println("CONSUMER-1: Book FOUND: \""
							+ BOOK_NAME_OLD + "\"");

					changeBookName(foundBook);

				} else {
					System.out.println("CONSUMER-1: Book NOT FOUND.");
				}
			}
		}
	}

	private void changeBookName(Book foundBook) {
		foundBook.setName(BOOK_NAME_NEW);
		System.out.println("CONSUMER-1: Book name CHANGED to: \""
				+ BOOK_NAME_NEW + "\"");
	}

	public void stop(BundleContext context) throws Exception {
		if (libService != null) {
			System.out.println("CONSUMER-1: ungetService() method called.");
			context.ungetService(libServiceRef);
			libService = null;
			libServiceRef = null;
			System.out.println("CONSUMER-1: stop() method finish.");
		}
	}
}
